<template>
  <div>
    <FixedOperation>
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <el-button type="primary" @click="handleSubmit">保存</el-button>
            <el-button type="primary" plain @click="handleReturn"
              >返回</el-button
            >
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container pay-form">
      <el-form
        ref="form"
        :model="formData"
        label-width="140px"
        :rules="formRules"
      >
        <el-row>
          <el-col :span="12" :offset="5">
            <el-form-item label="付款日期" prop="payDate">
              <el-date-picker
                v-model="formData.payDate"
                type="date"
                placeholder="请输入付款日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="付款金额" prop="price">
              <el-input v-model="formData.price" placeholder="请输入付款金额"
                ><template v-slot:append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="关联客户" prop="customerId">
              <el-select
                class="w-full"
                v-model="formData.customerId"
                placeholder="请输入客户名称检索客户"
                @focus="selectCustomerFn('customerId')"
              >
                <el-option
                  v-for="item in customerOption['customerId']"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
              <!-- <el-select
                v-model="formData.customerId"
                placeholder="请选择关联客户"
                class="w-full"
                filterable
                remote
                clearable
                @change="changeCustomer"
                :remote-method="queryCustomer"
                :loading="loadingSelect"
              >
                <el-option
                  v-for="item in parentOptions"
                  :key="item.id"
                  :label="item.customerName"
                  :value="item.id"
                >
                  <div>
                    <span>{{ item.customerName }}</span>
                    <span>({{ item.mainContactName }})</span>
                  </div>
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="关联订单" prop="orderId">
              <el-select
                v-model="formData.orderId"
                placeholder="请输入订单名称检索订单"
                class="w-full"
                suffix-icon="Search"
                remote-show-suffix
                :suffix-transition="false"
                filterable
                remote
                clearable
                @change="changeIndent"
                :remote-method="
                  val => queryIndentLimitEnt(val, formData.customerId)
                "
                :loading="loadingSelect"
              >
                <el-option
                  v-for="item in indentOptionLimitEnt"
                  :key="item.orderId"
                  :label="item.orderTitle"
                  :value="item.orderId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" :offset="5">
            <el-form-item label="付款期次" prop="payPlanId">
              <el-select
                class="w-full"
                v-model="formData.payPlanId"
                placeholder="请选择付款期次"
              >
                <el-option
                  v-for="item in payPlanOption"
                  :key="item.period"
                  :label="item.allPeriod"
                  :value="item.period"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12" :offset="5">
            <el-form-item label="结算方式" prop="settleType">
              <el-select
                class="w-full"
                v-model="formData.settleType"
                placeholder="请选择结算方式"
              >
                <el-option
                  v-for="item in settle_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="收款方式" prop="payType">
              <el-select
                class="w-full"
                v-model="formData.payType"
                placeholder="请选择收款方式"
              >
                <el-option
                  v-for="item in pay_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="收款人员" prop="_payUserId">
              <el-select
                class="w-full"
                v-model="formData._payUserId"
                placeholder="请选择收款人员"
                @focus="selectUserFn('payUserId')"
              >
                <el-option
                  v-for="item in userOption['payUserId']"
                  :key="item.uuid"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="备注信息" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="通知人员" prop="noticeUserArr">
              <el-select
                class="w-full"
                v-model="formData._noticeUserArr"
                placeholder="请选择通知人员"
                multiple
                @focus="selectUserFn('noticeUserArr')"
              >
                <el-option
                  v-for="item in userOption['noticeUserArr']"
                  :key="item.uuid"
                  :label="item.label"
                  :value="item.uuid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="5">
            <el-form-item label="" prop="">
              <span class="text-gray-300"
                >注：保存后，将自动通知到所选人员。</span
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
    ></SelectDialog>

    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @ok="selectCustomerData"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
    ></SelectCustomer>
  </div>
</template>
<script setup name="PayForm">
import { reactive, toRefs, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import usePassData from '@/store/modules/passData'
import FixedOperation from '@/components/FixedOperation'
import useCommonStore from '@/store/modules/common'
import { setPay, getPay } from '@/api/payManage/pay'
import { listSalesOrderSelect } from '@/api/indentManage/indent'
import {
  loadingSelect, //远程检索loading
  indentOptionLimitEnt, // 订单数据
  queryIndentLimitEnt // 检索订单数据
} from '@/hooks/dict/order'
import { getDetailTactlistByCactName } from '@/api/customerManage/customerList'
import useTagsViewStore from '@/store/modules/tagsView'
import { isMoneyNot } from '@/utils/validate'
import useUserStore from '@/store/modules/user'
import { getTreeNodeByParam, getPricipalId } from '@/utils/commo'
import { getWorkDay, getLatestMsg, addManage } from '@/api/system/notice'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const { proxy, type } = getCurrentInstance()
const payPlanOption = ref([]) //付款期次下拉
const userOption = ref({}) //通知人员下拉
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})
const { pay_type, settle_type } = proxy.useDict(
  'pay_type', //付款方式
  'settle_type' //结算方式
)

const props = defineProps({
  payData: {
    type: Object,
    require: true,
    default: null
  }
})
const data = reactive({
  formData: {
    customerType: 'customer'
  },

  formRules: {
    payDate: [
      {
        required: true,
        message: '请选择付款日期',
        trigger: 'change'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入付款金额',
        trigger: 'blur'
      },
      {
        validator: isMoneyNot
      }
    ],
    customerId: [
      {
        required: true,
        message: '请选择关联客户',
        trigger: 'change'
      }
    ],
    orderId: [
      {
        required: true,
        message: '请选择关联订单',
        trigger: 'change'
      }
    ],
    payPlanId: [
      {
        required: true,
        message: '请选择付款期次',
        trigger: 'change'
      }
    ],
    _payUserId: [
      {
        required: true,
        message: '请选择收款人员',
        trigger: 'change'
      }
    ]
  },

  dialogParam: {} /* 人员弹窗框参数 */,
  customerOption: {}, //客户选择下拉
  dialogParamA: {} /* 客户弹窗框参数 */
})
const { formData, formRules, dialogParam, customerOption, dialogParamA } =
  toRefs(data)
// watch(
//   () => data.formData.productInfoList,
//   (newVal, oldValue) => {
//     let price = 0
//     formData.value.productInfoList.forEach(e => {
//       if (e.id) {
//         price = e.price * e.num + price
//       }
//     })
//     formData.value.price = price
//   },
//   { deep: true }
// )
watchEffect(() => {
  if (route.query.payId && route.name == type.name) {
    console.log('instance.type.name-->', type.name)
    getFormData(route.query.payId)
  } else if (route.query.payData && route.name == type.name) {
    let payData = JSON.parse(route.query.payData)
    formData.value.customerId = payData.customerId
    formData.value.customerName = payData.customerName
    formData.value.orderId = payData.orderId
    formData.value.orderTitle = payData.orderTitle
    // formData.value.payPlanId = payData.period
    payData.customerId
      ? (customerOption.value['customerId'] = [
          {
            id: payData.customerId,
            label: payData.customerName
          }
        ])
      : ''
    payData.orderId
      ? (indentOptionLimitEnt.value = [
          {
            orderId: payData.orderId,
            orderTitle: payData.orderTitle
          }
        ])
      : ''
  }
})
/** 获取产品详情
 * @param {number}  id 表单id
 */
function getFormData(id) {
  proxy.$modal.loading('加载中')
  getPay(id).then(async res => {
    let resData = {}
    resData = res.data
    customerOption.value['customerId'] = [
      {
        label: resData.customerName, //? resData.customerName: resData.customerId,
        id: resData.customerId //? resData.customerId : resData.customerName
      }
    ]
    indentOptionLimitEnt.value = [
      {
        orderTitle: resData.orderTitle,
        orderId: resData.orderId
      }
    ]
    formData.value = resData
    proxy.$modal.closeLoading()
    // 获取项目负责人
    await getDefaultUserInfo(
      formData.value.payUserId,
      '_payUserId',
      'payUserId'
    )
    await getDefaultUserInfo(
      formData.value.noticeUserArr,
      '_noticeUserArr',
      'noticeUserArr'
    )
  })
}

// 初始化
function init() {}
// 保存
function handleSubmit(e) {
  console.log('保存-<>', formData.value)
  if (formData.value._payUserId) {
    formData.value.payUserId = getPricipalId(
      userOption.value['payUserId'],
      formData.value._payUserId
    ).toString()
  }
  if (formData.value._noticeUserArr.length > 0) {
    formData.value.noticeUserArr = getPricipalId(
      userOption.value['noticeUserArr'],
      formData.value._noticeUserArr
    )
  }
  proxy.$refs.form.validate((valid, msg) => {
    if (valid) {
      setPay(formData.value).then(res => {
        // proxy.$modal.msgSuccess(formData.value.id ? '修改成功' : '新增成功')
        // if (!formData.value.id) {
        //   useTagsViewStore().delView(router.currentRoute.value)
        //   router.go(-1)
        // }
        // 保存接口才有
        proxy.useReturn(
          '',
          () => {
            //返回上一步
            handleReturn()
          },
          async () => {
            //继续
          }
        )
        getFormData(res.data.id)
        // formData.value = res.data
        // console.log('res.data==>', res.data)
        let mesVoData = {
          businessId: '付款-通知-' + res.data.id, //业务ID
          content: `订单:'${res.data.orderTitle}'的付款消息`, //待办内容
          followDate: undefined, //跟进日期
          followType: undefined, //跟进方式
          impSign: '2', //重要程度:0-非常重要，1-重要，2-一般
          receiver: res.data.noticeUserArr.toString(), //接收人
          receiverName: undefined, //接收人中文
          reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
          sendTime: res.data.updateTime, //发送时间
          sender: res.data.updateBy, //发送人
          serviceType: '9', //业务类型:0-项目，1-订单，2-客户，3-工单，4-任务，5-产品，6-合同，7-公告，8-日程，9-付款, 10-联系人
          title: `订单:'${res.data.orderTitle}'的付款消息`, //待办标题
          type: undefined, //待办类型:0-普通，1-流程
          urgFlag: '2', //紧急程度:0-非常紧急，1-紧急，2-一般
          url: undefined, //待办链接(多链接用英文逗号隔开)
          urlName: undefined //待办链接名称(多链接名称用英文逗号隔开)
        }
        console.log('mesVoData==>', mesVoData)
        addManage(mesVoData)
      })
    }
  })
}

function handleReset() {
  console.log('清除')
  formData.value = {}
  proxy.resetForm('sortRef')
  //   proxy.$refs.form.resetForm()
}

/* 人员选择
 * @param {string}  keyName payUserId:收款人员  noticeUserArr:通知人员
 */
function selectUserFn(keyName) {
  dialogParam.value.type = keyName
  dialogParam.value.title =
    keyName == 'payUserId' ? '请选择收款人员' : '请选择通知人员'
  dialogParam.value.isDialog = true
  dialogParam.value.multiple = keyName == 'noticeUserArr'
  dialogParam.value.nodeKey = 'uuid'
  dialogParam.value.defaultCheckedKeys =
    keyName == 'payUserId'
      ? [formData.value[keyName]]
      : formData.value['_' + keyName]
  dialogParam.value.dataType = 'person'
}
// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'payUserId':
      userOption.value.payUserId = val.selectData
      formData.value.payUserName = val.labelData.toString()
      formData.value._payUserId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
    case 'noticeUserArr':
      userOption.value.noticeUserArr = val.selectData
      formData.value._noticeUserArr = val.defaultCheckedKeys
      break
  }
}

async function getDefaultUserInfo(val, fieldName, selectArr) {
  userOption.value[selectArr] = []
  let id = ''
  if (val) {
    id = val
  }
  //获取部门人员数据
  const deptUserData = await commonStore.getUseTreeData()
  if (Array.isArray(id)) {
    formData.value[fieldName] = []
    id.forEach(item => {
      let obj = getTreeNodeByParam(deptUserData, item, 'id', [])
      userOption.value[selectArr].push(...obj)
      formData.value[fieldName].push(obj[0].uuid)
    })
  } else {
    //根据当前用户id获取uuid
    let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
    userOption.value[selectArr] = obj
    formData.value[fieldName] = obj[0].uuid
  }
}

// 改变客户名称后
const changeCustomer = val => {
  formData.value.orderId = null
  queryIndentLimitEnt(undefined, val)
}
/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName) {
  switch (keyName) {
    case 'customerId':
      dialogParamA.value.type = keyName
      dialogParamA.value.tabVal = formData.value.customerType
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      dialogParamA.value.defaultCheckedKeys = formData.value[keyName]
      dialogParamA.value.defaultCheckedLabel = formData.value['customerName']
      dialogParamA.value.tabList = [
        {
          label: '企业客户',
          name: 'customer'
        },
        {
          label: '个人客户',
          name: 'cusLink'
        },
        {
          label: '内部单位',
          name: 'inner'
        }
      ]
      dialogParamA.value.dataType = 'person'
      break
  }
}

// 客户选择选择确定
const selectCustomerData = val => {
  switch (val.type) {
    case 'customerId':
      customerOption.value.customerId = val.selectData
      formData.value.customerType = val.tabVal
      formData.value.customerName = val.labelData.toString()
      if (formData.value.customerId !== val.defaultCheckedKeys.toString()) {
        changeCustomer(val.defaultCheckedKeys.toString())
      }
      formData.value.customerId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null

      break
    /* case 'transactionId':
      userOption.value.transactionId = val.selectData
      formData.value.transactionId = val.defaultCheckedKeys
      break */
  }
}

// 订单赋值
function changeIndent(row) {
  console.log('row==>', row)
  let newData = JSON.parse(JSON.stringify(indentOptionLimitEnt.value))
  let obj = newData.filter(item => {
    return item.orderId == row
  })
  formData.value.orderTitle = obj[0].orderTitle
  // payPlanOption.value = obj[0].payPlanList
}
// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

init()
</script>
<style scoped>
.form-title {
  color: #111111;
}
.pay-form:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}
</style>
